package com.lahui.camera

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.camera2.*
import android.hardware.camera2.params.OutputConfiguration
import android.hardware.camera2.params.SessionConfiguration
import android.hardware.camera2.params.StreamConfigurationMap
import android.os.*
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.util.Size
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Button
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {

    private lateinit var btnCamera: Button
    private lateinit var surfaceView: SurfaceView
    private var surfaceCreated = false
    private val TAG = "LaHuiExample"
    private lateinit var mCamera: CameraDevice

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findView()

        requestCameraPermission()
    }

    private val REQUEST_CODE = 101
    private fun requestCameraPermission() {
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            return
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {//有权限

        } else {//无权限，去申请
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CODE)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //有权限
            }else{//无权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                    //用户拒绝权限
                }else{//用户拒绝且不再提醒
                    //这里就不多赘述了。只做同意的部分了
                }
            }
        }
    }

    private fun openCamera() {
        if (!surfaceCreated) {
            return
        }

        var cameraManager: CameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val cameraIdList = cameraManager.cameraIdList
        if (cameraIdList.isNotEmpty()) {
            if (ActivityCompat.checkSelfPermission(
                            this,
                            Manifest.permission.CAMERA
                    ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }
            val cameraId = cameraIdList[0]

            //这里可以设置相机的特性，比如说曝光，打开手电，对焦等等

            cameraManager.openCamera(cameraId, object : CameraDevice.StateCallback() {
                @RequiresApi(Build.VERSION_CODES.P)
                override fun onOpened(camera: CameraDevice) {
                    Log.d(TAG, "onOpened")
                    mCamera = camera

                    camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
                            .addTarget(surfaceView.holder.surface)

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        var surfaceList: MutableList<OutputConfiguration> = ArrayList()
                        var outputConfiguration =
                                OutputConfiguration(surfaceView.holder.surface)
                        surfaceList.add(outputConfiguration)

                        var session = SessionConfiguration(
                                SessionConfiguration.SESSION_REGULAR,
                                surfaceList, {
                            Log.d(TAG, "execute")
                            //这里一定要调用run方法，不然下面的CameraCaptureSession.StateCallback.onConfigured是不会有回调的
                            it.run()
                        }, callback
                        )
                        camera.createCaptureSession(session)
                    } else {
                        var surfaceList: MutableList<Surface> = ArrayList()
                        surfaceList.add(surfaceView.holder.surface)

                        camera.createCaptureSession(
                                surfaceList,
                                callback,
                                handler
                        )
                    }
                }

                override fun onDisconnected(camera: CameraDevice) {
                    Log.d(TAG, "onDisconnected")
                }


                override fun onError(camera: CameraDevice, error: Int) {
                    Log.d(TAG, "onError")
                }

            }, handler)

        }
    }

    var callback = object : CameraCaptureSession.StateCallback() {
        override fun onConfigured(captureSession: CameraCaptureSession) {
            Log.d(TAG, "StateCallback.onConfigured")
            val createCaptureRequest =
                    mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
            //这句不加会报错，这个是要一个目标的surface，我们这里用的是surfaceView
            createCaptureRequest.addTarget(surfaceView.holder.surface)
            //预览请求，captureSession.setSingleRepeatingRequest这个是图片预览
            //captureSession.setRepeatingRequest请求的是视频预览
            captureSession.setRepeatingRequest(
                    createCaptureRequest.build(),
                    object : CameraCaptureSession.CaptureCallback() {
                        override fun onCaptureCompleted(
                                session: CameraCaptureSession,
                                request: CaptureRequest,
                                result: TotalCaptureResult
                        ) {

                        }
                    }, handler
            )
        }

        override fun onConfigureFailed(session: CameraCaptureSession) {
            Log.d(TAG, "StateCallback.onConfigureFailed")
        }
    }

    private fun findView() {
        btnCamera = findViewById(R.id.btn_open_camera)
        surfaceView = findViewById(R.id.surfaceview)

        surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                Log.d(TAG, "surfaceCreated")
                surfaceCreated = true
            }

            override fun surfaceChanged(
                    holder: SurfaceHolder,
                    format: Int,
                    width: Int,
                    height: Int
            ) {
                Log.d(TAG, "surfaceChanged")
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                Log.d(TAG, "surfaceDestroyed")

            }
        })


        btnCamera.setOnClickListener {
            openCamera()
        }
    }


    private var handler: Handler = Handler(Looper.myLooper()!!) {
        Log.d(TAG, "handleMessage")
        false
    }


}